package com.example.demo.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.*;

/**
 * @Classname ParamsSignUtil
 * @Description 请求参数签名工具类
 * @Date 2019/8/20 16:50
 * @Created by yby
 */
public class ParamsSignUtil {

    public static void main(String[] args) {


        //返回集合
        JSONArray jsonArray = new JSONArray();
        //福彩数据
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("buyType", "1");  //1为福彩
        jsonObject.put("buyNumber", 22);  //购买数量
        //jsonObject.put("welfareType","10元"); //福彩类型
        jsonObject.put("welfareSize", 11); //福彩尺寸

        //jsonArray.put(jsonObject);
        jsonArray.add(jsonObject);

        //体彩数据
        jsonObject = new JSONObject();
        jsonObject.put("buyType", "2");//2为体彩
        jsonObject.put("buyNumber", 33);//购买数量
        //jsonObject.put("sportsType","5元"); //体彩类型
        jsonObject.put("sportsSize", 11); //体彩尺寸
        //jsonArray.put(jsonObject);
        jsonArray.add(jsonObject);

        //参数签名算法测试例子
        HashMap<String, String> signMap = new HashMap<String, String>();
        signMap.put("cpOdd", "12AAFF");
        signMap.put("orderId", "15683");
        signMap.put("param", jsonArray.toJSONString());
        //signMap.put("time",String.valueOf(System.currentTimeMillis()));
        signMap.put("time", "1567477313594");
        String secret_key = "02f7e697217940d08a48aa0be96962ee"; //加密secret
        System.out.println("参数类型signMap=" + signMap.toString());
        System.out.println("时间戳：" + System.currentTimeMillis());
        System.out.println("得到签名sign1:" + getSign(signMap, secret_key));
        HashMap<String, String> SignHashMap = ParamsSignUtil.sign(signMap, secret_key);
        //System.out.println("SignHashMap:"+SignHashMap);
        //System.out.println("参数:"+jsonArray.toJSONString());
        String sign = (String) SignHashMap.get("appSign");
        //获取参数签名字符串
        System.out.println("得到签名sign2:" + sign);


    }

    public static HashMap<String, String> sign(Map<String, String> paramValues,
                                               String secret) {
        return sign(paramValues, null, secret);
    }

    /**
     * @param paramValues
     * @param ignoreParamNames
     * @param secret
     * @return
     */
    public static HashMap<String, String> sign(Map<String, String> paramValues,
                                               List<String> ignoreParamNames, String secret) {
        try {
            HashMap<String, String> signMap = new HashMap<String, String>();
            StringBuilder sb = new StringBuilder();
            List<String> paramNames = new ArrayList<String>(paramValues.size());
            paramNames.addAll(paramValues.keySet());
            if (ignoreParamNames != null && ignoreParamNames.size() > 0) {
                for (String ignoreParamName : ignoreParamNames) {
                    paramNames.remove(ignoreParamName);
                }
            }
            Collections.sort(paramNames);
            sb.append(secret);
            for (String paramName : paramNames) {
                sb.append(paramName).append(paramValues.get(paramName));
            }
            sb.append(secret);
            byte[] md5Digest = getMD5Digest(sb.toString());
            String sign = byte2hex(md5Digest);
            signMap.put("appParam", sb.toString());
            signMap.put("appSign", sign);
            return signMap;
        } catch (IOException e) {
            throw new RuntimeException("加密签名计算错误", e);
        }

    }

    public static String utf8Encoding(String value, String sourceCharsetName) {
        try {
            return new String(value.getBytes(sourceCharsetName), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new IllegalArgumentException(e);
        }
    }


    private static byte[] getMD5Digest(String data) throws IOException {
        byte[] bytes = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            bytes = md.digest(data.getBytes("UTF-8"));
        } catch (GeneralSecurityException gse) {
            throw new IOException(gse);
        }
        return bytes;
    }


    private static String byte2hex(byte[] bytes) {
        StringBuilder sign = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() == 1) {
                sign.append("0");
            }
            //sign.append(hex.toUpperCase());
            sign.append(hex.toLowerCase());
        }
        return sign.toString();
    }

    public static String getSign(Map<String, String> params, String secret) {
        String ret = "";
        StringBuilder sb = new StringBuilder();
        Set<String> keyset = params.keySet();
        TreeSet<String> sortSet = new TreeSet<String>();
        sortSet.addAll(keyset);
        Iterator<String> it = sortSet.iterator();
        sb.append(secret);
        while (it.hasNext()) {
            String key = it.next();
            String value = params.get(key);
            sb.append(key).append(value);
        }
        sb.append(secret);
        byte[] md5Digest;
        try {
            md5Digest = getMD5Digest(sb.toString());
            ret = byte2hex(md5Digest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ret;
    }

}
